<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<title></title>
<style>
	.tbhead{
		background: #ccc;
		text-align: center;
		color: red;
	}
	.datarow{
		text-align: center;
		color: blueviolet;
	}
	.txt{
		width: 100px;
	}
</style>

</head>
<body>
	<h2>学生信息管理</h2>
	<input type="button" id="btfind" value="查询">&nbsp;
	<input type="button" id="btadd" value="新增" style="display: inline;">&nbsp;
	<input type="button" id="btdel" value="删除"style="display: inline;">&nbsp;
	<input type="button" id="btchange" value="修改"style="display: inline;">&nbsp;
	</br></br>
	学号：<input type="text" name="sid" id="sid" class="txt">&nbsp;
	姓名：<input type="text" name="sname" id="sname" class="txt">&nbsp;
	性别：<select id="sex">
		<option value="男" selected="selected">男</option>
		<option value="女">女</option>
	</select>&nbsp;
	</br></br>
	
	
	<table width="60%" border="1" cellpadding="0" cellspacing="0" id="studtable">
		<tr class="tbhead">
			<td>选择</td>
			<td>学号</td>
			<td>姓名</td>
			<td>性别</td>
		</tr>
		
	</table>
<script>
	$(function(){
		var students=[];
		$.getJSON('student.json','', function(data){
			// console.log(data)
			// data.student.forEach(o=>appendStu(o));
			data.student.forEach(o=>students.push(o));
			 // console.log(students+"in")
			show(students);
		})
		//新增
		$('#btadd').click(function(){
			let sid=$('#sid').val();
			let sname=$('#sname').val();
			let sex=$('select>option:selected').val();
			let stu=new Student(sid,sname,sex);
			students.push(stu);
			show(students);
		})
		//查询
		$('#btfind').click(function(){
			let sid=$('#sid').val();
			let sname=$('#sname').val();
			let sex=$('select>option:selected').val();
			let findStu=students.filter(o=>o.id==sid&&o.name==sname&&o.sex==sex);
			sid==''&&sname==''? show(students):show(findStu)
			

		})
		//删除
		$('#btdel').click(function(){
			// $(':checkbox:checked').get().forEach(o=>students.splice(o.num,1));
			$(':checkbox:checked').get().reverse().forEach(o=>students.splice(o.num,1));
			show(students);
			
		
		})	
		
		
		function Student(id,name,sex){
			this.id=id;
			this.name=name;
			this.sex=sex;
		}
		
		
		function show(students){
			$('.datarow').remove();
			students.forEach(o=>appendStu(o));
			$(':checkbox').each((i,item)=>item.num=i)
			
			
			// $(':checkbox').each(i=>this.num=i)

			// $(':checkbox').each(function(i){
			// 	this.num=i;
			// })
			
		}
		function appendStu(Obj){
			let tr=`
			<tr class="datarow">
				<td><input type='checkbox'></td>
				<td>${Obj.id}</td>
				<td>${Obj.name}</td>
				<td>${Obj.sex}</td>
			</tr>
			`
			$('table').append(tr)
		}
	})
</script>
</body>
</html>
